package cn.learn.controller.system.user;

import cn.learn.base.BaseController;
import cn.learn.domain.system.dept.Dept;
import cn.learn.domain.system.role.Role;
import cn.learn.domain.system.user.User;
import cn.learn.domain.system.wxuser.WxUser;
import cn.learn.utils.FileUploadUtil;
import cn.learn.service.system.dept.DeptService;
import cn.learn.service.system.role.RoleService;
import cn.learn.service.system.user.UserService;
import cn.learn.service.system.wxuser.WxUserService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;
    @Autowired //rabbitmq的模板对象
    private AmqpTemplate amqpTemplate;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private FileUploadUtil fileUploadUtil;

    /**
     * 用户分页数据查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list", name = "查询用户")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo resultData = userService.selectAllByPage(pageNum, pageSize, companyId);
        request.setAttribute("pageList", resultData);
        return "/system/user/user-list";
    }

    /**
     * 添加一条用户 与 跳转到用户展示界面
     * @param user
     * @return
     */
    @RequestMapping(value = "/addOne", name = "添加用户")
    public String addOne(User user) {
        if (request.getMethod().equals("POST")) {
            String uid = UUID.randomUUID().toString().replace("-", "");
            user.setId(uid);
            String MD5password = new Md5Hash(user.getPassword(), user.getEmail(), 1).toString();
            user.setPassword(MD5password);
            user.setCompanyId(companyId);
            user.setCompanyName(companyName);
            userService.addOne(user);
            // 给注册的邮箱发短信 （把发短信的任务交给消息中间件执行--5s）
                // 调用消息中间件(发邮件)
                // 参数1：routingkey==email==useremailjhj==useremail
                // 参数2：N个参数
            Map<String,String> map=new HashMap();
            map.put("email",user.getEmail());
            map.put("emailMsg","邮件测试成功！...");
            amqpTemplate.convertAndSend("email",map);
            return "redirect:/system/user/list.do";
        }
        List<Dept> depts = deptService.selectAll(companyId);
        request.setAttribute("deptList", depts);
        return "/system/user/user-add";
    }

    /**
     * 修改用户 与 跳转到修改页面
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateOne", name = "修改用户")
    public String updateOne(User user) {
        if (request.getMethod().equals("POST")) {
            user.setCompanyId(companyId);
            user.setCompanyName(companyName);
            String MD5password = new Md5Hash(user.getPassword(), user.getEmail(), 1).toString();
            user.setPassword(MD5password);
            userService.updateOneByID(user);

            WxUser wxUser = new WxUser();
            System.out.println(user.getEmail());
            User oneById = userService.findOneById(user);
            String openid = oneById.getOpenid();
            System.out.println(openid);
            wxUser.setEmail(user.getEmail());
            wxUser.setOpenid(openid);
            wxUserService.upDateByUser(wxUser);
            return "redirect:/system/user/list.do";
        }
        User resultData = userService.findOneById(user);
        List<Dept> depts = deptService.selectAll(companyId);
        request.setAttribute("data", resultData);
        request.setAttribute("deptList", depts);
        return "/system/user/user-update";
    }

    /**
     * 根据id删除一条用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", name = "删除用户")

    public String delete(String id) {
        userService.deleteById(id);
       User user = (User)session.getAttribute("user");
        String openid = user.getOpenid();
        if (openid!=null){
            wxUserService.deleteUserOd(openid);

        }

        return "redirect:/system/user/list.do";
    }

    /**
     * 跳转到用户设置角色界面
     * @param id
     * @return
     */
    @RequestMapping(value = "/roleList", name = "跳转到用户角色设置界面")
    public String roleList(String id) {
        User user = new User();
        user.setId(id);
        // 用户信息
        User resultUser = userService.findOneById(user);
        // 企业所有权限
        List<Role> resultRole = roleService.selectAll(companyId);
        // 用户权限
        List<Role> userRole = roleService.selectUserRole(id);
        request.setAttribute("data", resultUser);
        request.setAttribute("roleList", resultRole);
        request.setAttribute("userRoleStr", userRole);
        return "/system/user/user-role";
    }

    /**
     * 修改用户拥有的权限
     * @param userId
     * @param roleIds
     * @return
     */
    @RequestMapping(value = "/changeRole", name = "修改用户角色")
    public String changeRole(String userId, String[] roleIds) {
        roleService.updateUserRole(userId, roleIds);
        return "redirect:/system/user/list.do";
    }

    /**
     * 跳转页面
     * @return
     */
    @RequestMapping(value = "/toUpdate", name = "修改个人信息")
    public String toUpdate(){
        String loginPassword = (String) session.getAttribute("loginPassword");
        User loginUser = (User)session.getAttribute("user");
        loginUser.setPassword(loginPassword);
        request.setAttribute("userInfo",loginUser);
        return "/system/user/message";
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/updateUser", name = "修改个人信息")
    public String updateUser(User user, MultipartFile imgs) throws Exception {
        User loginUser = (User) session.getAttribute("user");
        loginUser.setUserName(user.getUserName());
        loginUser.setEmail(user.getEmail());
        loginUser.setGender(user.getGender());
        loginUser.setTelephone(user.getTelephone());
        loginUser.setBirthday(user.getBirthday());
        loginUser.setRemark(user.getRemark());
        String imgsrc = fileUploadUtil.upload(imgs);
        // 保存, 设置下图片地址
        loginUser.setImg("http://"+imgsrc);
        return "home/home";
    }

}
